<template>
  <!--利用element-ui的局部loading作为mask遮罩层-->
  <div class="consumer-page activity-list-page">
    <div class="mask" v-show="showMask" @click="showMask=false"></div>
    <div class="big-image"
         v-show="showMask"
         @click="showMask=false">
      <img :src="bigImageUrl" style="width:800px;minHeight:600px;borderRadius:20px" alt="">
    </div>
    <!--头部标题-->
    <el-breadcrumb separator="/" class="page-title">
      <el-breadcrumb-item :to="{ path: 'shopAdIndex' }">Shop</el-breadcrumb-item>
      <el-breadcrumb-item>View</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="search-box">
      <el-form :inline="true" label-position="top" :model="submitForm" size="mini" ref="ruleForm"
               class="demo-ruleForm main-search-box" v-loading.fullscreen.lock="fullscreenLoading">
        <!--数据库状态-->
        <el-form-item label="Ad Status" style="width: 200px;margin-right: 10px">
          <el-select style="width: 200px;" class="editStyle" v-model=" submitForm.status" placeholder="" disabled>
            <el-option v-for="i in statusOption" :key="i.value" :label="i.label" :value="i.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 商品类别级联菜单 -->
        <!--第一级菜单-->
        <el-form-item label="Category1" style="width: 200px;margin-right: 10px" v-if="firstCategory">
          <el-input v-model="firstCategory" disabled></el-input>
        </el-form-item>
        <!--第二级菜单-->
        <el-form-item label="Category2" style="width: 200px;margin-right: 10px" v-if="secondaryCategory">
          <el-input v-model="secondaryCategory" disabled></el-input>
        </el-form-item>
        <!--第三级菜单-->
        <el-form-item label="Category3" style="width: 200px;margin-right: 10px" v-if="thirdCategory">
          <el-input v-model="thirdCategory" disabled></el-input>
        </el-form-item>
        <!-- 显示图片 -->
        <p>Upload Photos</p>
        <section class="img-area clearfix">
          <div class="img-wraper">
            <img :src="showPhoto[0].url" alt="Ad Photo" v-if="showPhoto[0].url"
                 @click="showBigImage(showPhoto[0].url)"
                 style="width:100px;height:100px;borderRadius:5px;"/>
          </div>
          <div class="img-wraper">
            <img :src="showPhoto[1].url" alt="Ad Photo" v-if="showPhoto[1].url"
                 @click="showBigImage(showPhoto[1].url)"
                 style="width:100px;height:100px;borderRadius:5px;"/>
          </div>
          <div class="img-wraper">
            <img :src="showPhoto[2].url" alt="Ad Photo" v-if="showPhoto[2].url"
                 @click="showBigImage(showPhoto[2].url)"
                 style="width:100px;height:100px;borderRadius:5px;"/>
          </div>
          <div class="img-wraper">
            <img :src="showPhoto[3].url" alt="Ad Photo" v-if="showPhoto[3].url"
                 @click="showBigImage(showPhoto[3].url)"
                 style="width:100px;height:100px;borderRadius:5px;"/>
          </div>
          <div class="img-wraper">
            <img :src="showPhoto[4].url" alt="Ad Photo" v-if="showPhoto[4].url"
                 @click="showBigImage(showPhoto[4].url)"
                 style="width:100px;height:100px;borderRadius:5px;"/>
          </div>
          <div class="img-wraper">
            <img :src="showPhoto[5].url" alt="Ad Photo" v-if="showPhoto[5].url"
                 @click="showBigImage(showPhoto[5].url)"
                 style="width:100px;height:100px;borderRadius:5px;"/>
          </div>
          <div class="img-wraper">
            <img :src="showPhoto[6].url" alt="Ad Photo" v-if="showPhoto[6].url"
                 @click="showBigImage(showPhoto[6].url)"
                 style="width:100px;height:100px;borderRadius:5px;"/>
          </div>
          <div class="img-wraper">
            <img :src="showPhoto[7].url" alt="Ad Photo" v-if="showPhoto[7].url"
                 @click="showBigImage(showPhoto[7].url)"
                 style="width:100px;height:100px;borderRadius:5px;"/>
          </div>
        </section>
        <!--</div>-->
        <!--标题-->
        <el-row>
          <el-form-item label="Title" style="width: 200px;margin-right: 10px" prop="title">
            <el-input
              type="textarea"
              :rows="4"
              placeholder=""
              v-model="submitForm.title"
              style="width:300px"
              disabled
            >
            </el-input>
          </el-form-item>
        </el-row>
        <!--价格和单位-->
        <el-row>
          <el-form-item label="Price" style="width: 150px;">
            <el-input v-model="submitForm.price" placeholder="" disabled></el-input>
          </el-form-item>
          <el-form-item label="Unit" style="width: 200px;margin-right: 10px">
            <el-select style="width: 80px" v-model="submitForm.priceType" placeholder="" disabled>
              <el-option v-for="i in unitOption" :key="i.value" :label="i.label" :value="i.value"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!--状况-->
        <el-row>
          <el-form-item label="Condition" style="width: 200px;margin-right: 10px">
            <el-radio v-model="submitForm.condition" label="0" disabled>New</el-radio>
            <el-radio v-model="submitForm.condition" label="1" disabled>Used</el-radio>
          </el-form-item>
        </el-row>
        <!--描述-->
        <el-form-item label="Description" style="width: 200px;margin-right: 10px">
          <el-input
            type="textarea"
            :rows="4"
            placeholder=""
            v-model="submitForm.desc"
            disabled
            style="width:300px">
          </el-input>
        </el-form-item>
        <!--位置-->
        <el-row>
          <el-form-item label="Region">
            <el-select style="width: 200px" v-model="submitForm.regionId" placeholder="" disabled>
              <el-option v-for="rg in regions" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Township">
            <el-select style="width: 200px" v-model="submitForm.townshipId" placeholder="" disabled>
              <el-option v-for="ts in townships" :key="ts.value" :label="ts.text" :value="ts.value"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!--规格选择-->
        <el-row v-if="propertyData.length>0" v-for="item in propertyData" :key="item.id">
          <!--长度大于1就显示为下拉框-->
          <el-form-item v-if="item.values.length>1" :label="item.name" style="width: 200px;margin-right: 10px">
            <el-select style="width: 200px" v-model="otherForm[item.id]" placeholder="" disabled>
              <el-option v-for="i in item.values" :key="i.id" :label="i.text" :value="i.text"></el-option>
            </el-select>
          </el-form-item>
          <!--否则就显示成输入框-->
          <el-form-item v-else :label="item.name" style="width: 200px;">
            <el-input v-model="otherForm[item.id]" placeholder="" disabled></el-input>
          </el-form-item>
        </el-row>
        <!--备注-->
        <el-form-item label="Notes" style="width: 200px;margin-right: 10px">
          <el-input
            type="textarea"
            :rows="4"
            placeholder=""
            v-model="submitForm.notes"
            disabled
            style="width:300px">
          </el-input>
        </el-form-item>
      </el-form>
      <!--拒绝和验证-->
      <el-row :gutter="40" type="flex" justify="center" style="padding:40px 0;">
        <el-col :span="6">
          <el-button size="medium" style="width:100%" @click="cancelPutForm" type="info">Cancel</el-button>
        </el-col>
        <el-col :span="6">
          <!--只有ad status为pending(7)或reported(8)且审核状态为notsure（2）或未审核（0）时 显示审核按钮-->
          <el-button size="medium" style="width:100%" type="success" @click="toVerify"
                     v-if="(verificationStatus==2||verificationStatus==0)&&(submitForm.status==7||submitForm.status==8)">
            Verify
          </el-button>
          <el-button size="medium" style="width:100%" type="warning" disabled v-else>Have Verified</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" v-loading="tableLoading" border style="width: 100%">
        <el-table-column prop="adStatus" label="Ad Status" align="center" min-width="120">
          <template slot-scope="scope">
            <p>{{getStatus(scope.row.adStatus)}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="verificationStatus" label="Verification Status" align="center" min-width="150">
          <template slot-scope="scope">
            <p>{{getVerifyStatus(scope.row.verificationStatus)}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="suspendedReason" label="Suspended Reason" align="center" min-width="140">
        </el-table-column>
        <el-table-column prop="params" label="Sql" align="center" min-width="300">
        </el-table-column>
        <el-table-column prop="notes" label="Notes" align="center" min-width="100">
        </el-table-column>
        <el-table-column prop="updateDatetime" label="Updated Date" align="center" min-width="160">
          <template slot-scope="scope">
            <p>{{dateFormat(scope.row.updateDatetime)}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="Updated By" align="center" min-width="120">
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="block" style="margin-top: 15px;text-align: center;">
        <el-pagination @size-change="handleChangeSize" @current-change="handleChangePage"
                       :current-page="pageData.pageNum" :page-size="pageData.pageSize"
                       :page-sizes="[10, 20, 50, 100, 500]" :page-count="pageInfo.totalPages"
                       :total="pageInfo.totalCount" layout="total, prev, pager, next, jumper, sizes">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import {getShopViewData, getAdViewTable} from '../../api/guc_api.js';
  import {getCarModelData} from '../../api/zxy_api.js';
  import regions from '@/json/region';
  import townships from '@/json/township';
  import categoryData from '@/json/category.json';
  import phoneBrand from '@/json/phoneBrand';
  import carBrand from '@/json/carBrand';


  export default {
    name: 'shopAdView',
    data() {
      return {
        //控制遮罩层。。
        showMask: true,
        //显示图片的数组
        showPhoto: [
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
        ],
        // 需要提交的数据
        submitForm: {
          title: '',
          price: 0,
          regionId: 0,
          townshipId: 0,
          //默认是active
          status: '',
          //标题，价格，单位，状况 ，描述,备注
          title: '',
          price: '',
          priceType: '',
          condition: '',
          desc: '',
          notes: '',
          //位置
          regionId: '',
          townshipId: '',
          //商品规格数据
          values: []
        },
        //目录
        firstCategory: '',
        secondaryCategory: '',
        thirdCategory: '',
        // 本地数据
        categoryData,
        regions,
        townships,
        phoneBrand,
        carBrand,
        secondaryData: [],
        thirdData: [],
        //属性数据
        propertyData: [],
        // 位置
        townshipData: [],
        selectedTownship: '',
        //仓库状态数据
        statusOption: [
          {
            label: 'Active',
            value: 1,
          },
          {
            label: 'Draft',
            value: 2,
          },
          {
            label: 'Sold',
            value: 3,
          },
          {
            label: 'Deleted',
            value: 4,
          },
          {
            label: 'Rejected',
            value: 5,
          },
          {
            label: 'Inactive',
            value: 6,
          },
          {
            label: 'Pending',
            value: 7,
          },
          {
            label: 'Reported',
            value: 8,
          },
        ],
        //单位数据
        unitOption: [
          {
            label: 'Kyat',
            value: '1',
          },
          {
            label: 'Lakh',
            value: '2',
          },
          {
            label: 'Usd',
            value: '3',
          },
        ],
        // 提交商品后拿到的店铺id
        goodsId: '',
        //表格加载动画
        tableLoading: false,
        //满屏加载动画
        fullscreenLoading: false,
        otherForm: {},
        showImages: [],
        //审核状态
        verificationStatus: '',
        categoryId: '',
        //表格数据
        tableData: [],
        //预览大图
        showMask: false,
        bigImageUrl: '',
        pageData: {
          //页数
          pageNum: 1,
          //没页数据条数
          pageSize: 10,
        },
        pageInfo: {
          //总数据条数
          totalCount: 0,
          //总页数
          totalPages: 0,
        },
      }
    },
    methods: {
      //日期格式化
      dateFormat(value) {
        let date = new Date(value);
        let Y = date.getFullYear();
        let m = date.getMonth() + 1;
        let d = date.getDate();
        let H = date.getHours();
        let i = date.getMinutes();
        let s = date.getSeconds();
        if (m < 10) {
          m = '0' + m;
        }
        if (d < 10) {
          d = '0' + d;
        }
        if (H < 10) {
          H = '0' + H;
        }
        if (i < 10) {
          i = '0' + i;
        }
        if (s < 10) {
          s = '0' + s;
        }
        let t = Y + '-' + m + '-' + d + '  ' + H + ':' + i + ':' + s;
        return t;
      },
      //仓库状态格式化
      getStatus(value) {
        if (value === 1) {
          return 'Active';
        }
        else if (value === 2) {
          return 'Draft';
        }
        else if (value === 3) {
          return 'Sold';
        }
        else if (value === 4) {
          return 'Deleted';
        }
        else if (value === 5) {
          return 'Rejected';
        }
        else if (value === 6) {
          return 'Inactive';
        }
        else if (value === 7) {
          return 'Pending';
        }
        else if (value === 8) {
          return 'Reported';
        }
      },
      //审核状态初始化
      getVerifyStatus(value) {
        if (value == 0) {
          return 'Null'
        }
        else if (value == 1) {
          return 'Approved'
        }
        else if (value == 2) {
          return 'Not Sure'
        }
        else if (value == 3) {
          return 'Rejected'
        }

      },
      //错误提示信息
      messageToastErr(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'error'
        })
      },
      //成功消息提示
      messageToastSuccess(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'success'
        })
      },
      //显示大图
      showBigImage(url) {
        this.showMask = true
        this.bigImageUrl = url
      },
      //每页显示条数改变后调用
      handleChangeSize(val) {
        this.pageData.pageSize = parseInt(val);
        this.pageData.pageNum = 1;
        this.initTable();
      },
      //页数改变后调用
      handleChangePage(val) {
        this.pageData.pageNum = val;
        this.initTable();
      },
      initForm() {
        this.fullscreenLoading = true
        // 初始化表单数据
        getShopViewData({goodsId: this.goodsId})
          .then(res => {
            this.fullscreenLoading = false
            this.tableLoading = false
            let obj = res.data.object
            this.submitForm.status = obj.status
            this.submitForm.title = this.$translateLang(obj.title || '', 'unicodeTozawgyi') || ''
            this.submitForm.price = obj.price
            this.submitForm.priceType = obj.priceType + ''
            this.submitForm.condition = obj.condition + ''
            this.submitForm.desc = this.$translateLang(obj.desc || '', 'unicodeTozawgyi') || ''
            this.submitForm.regionId = obj.regionId
            this.gettownships()
            this.submitForm.townshipId = obj.townshipId
            this.submitForm.notes = this.$translateLang(obj.notes || '', 'unicodeTozawgyi') || ''
            // 初始化category
            let categoryName = obj.category.categoryName
            let categoryArr = categoryName.split('/')
            this.firstCategory = categoryArr[0] || ''
            this.secondaryCategory = categoryArr[1] || ''
            this.thirdCategory = categoryArr[2] || ''
            //初始化规格
            this.getPropertyData(obj.categoryId)
            obj.values.forEach(item => {
              this.otherForm[item.propertyId] = this.$translateLang(item.text || '', 'unicodeTozawgyi') || ''
            })
            //初始化审核状态
            this.verificationStatus = obj.verificationStatus
            //图片数据初始化
            if (obj.images.length > 0) {
              obj.images.forEach(item => {
                let obj = {}
                obj.id = item.id
                obj.url = item.url || ''
                this.showPhoto[item.sequence] = obj
              })
            }
          })
          .catch(error => {
            this.fullscreenLoading = false
            console.log(error)
          })
      },
      initTable() {
        // 初始化表格数据
        this.tableLoading = true
        getAdViewTable(Object.assign({goodsId: this.goodsId}, this.pageData))
          .then(res => {
            this.tableLoading = false
            if (res.data.errorID == 0) {
              this.tableData = res.data.object.list
              this.pageInfo.totalCount = res.data.object.total
              this.pageInfo.totalPages = res.data.object.pages
            }
            else {
              this.tableLoading = false
              this.messageToastErr(res.data.message)
            }
          })
          .catch(error => {
            this.tableLoading = false
            console.log(error)
          })
      },
      // 获取township数据
      gettownships() {
        this.submitForm.townshipId = ''
        let townData = []
        this.townships.forEach((item) => {
          if (item.regionId === this.submitForm.regionId) {
            townData.push(item)
          }
        })
        this.townshipData = townData
      },
      //获取规格数据
      getPropertyData(res) {
        let catId = res ? res : this.categoryId
        for (let i = 0; i < this.categoryData.length; i++) { // 属性层级一
          if ((catId === this.categoryData[i].id) && this.categoryData[i].properties) {
            this.formatPropertyData(this.categoryData[i].properties);
            this.propertyData = this.categoryData[i].properties;
          } else {
            if (this.categoryData[i].children.length > 0) {
              for (let j = 0; j < this.categoryData[i].children.length; j++) {  // 属性层级二
                if ((catId === this.categoryData[i].children[j].id) && this.categoryData[i].children[j].properties) {
                  // id为142(对应的是mobiephone)时数据额外处理
                  if (catId == '142') {
                    let arr = [];
                    //先拿到mobile storage数据
                    arr = arr.concat([], this.categoryData[i].children[j].properties);
                    //然后拿到brand数据
                    let brandData = this.phoneBrand.properties
                    //最后根据brandId调后台接口拿到model数据
                    let obj = {
                      "id": 57,
                      "name": "Mobile Model",
                      "values": []
                    }
                    arr.unshift(obj)
                    arr.unshift(brandData);
                    this.formatPropertyData(arr);
                    this.propertyData = arr;
                  }else if(catId == '227'){
                    let arr = [];
                    //先拿到car storage数据
                    arr = arr.concat([], this.categoryData[i].children[j].properties);
                    //最后根据brandId调后台接口拿到model数据
                    let obj = {
                      "id": 55,
                      "name": "Car Model",
                      "values": []
                    }
                    // 编辑初始化页面时,需要获取当前brand对应的model数据
                    if (typeof(values) == 'object' && values.length > 0) {  // 编辑的时候让model属性可以显示出来
                      for (let i = 0; i < values.length; i++) {
                        if (values[i].propertyId == '17') {
                          // 请求model数据
                          getCarModelData({carPropertyId: values[i].valueId}).then((res) => {
                            if(res.data.errorID==0){
                              obj['values'] = res.data.object;
                            }
                            else{
                              this.messageToastErr(res.data.message)
                            }
                          }).catch((e) => {
                            console.log(e)
                          })
                        }
                      }
                    }
                    arr.unshift(obj)
                    arr.unshift(this.carBrand.properties);
                    this.formatPropertyData(arr);
                    this.propertyData = arr;
                  }
                  else {
                    this.formatPropertyData(this.categoryData[i].children[j].properties);
                    this.propertyData = this.categoryData[i].children[j].properties;
                  }
                } else {
                  if (this.categoryData[i].children[j].children.length > 0) {
                    for (let k = 0; k < this.categoryData[i].children[j].children.length; k++) {  // 属性层级三
                      if ((catId === this.categoryData[i].children[j].children[k].id) && this.categoryData[i].children[j].children[k].properties) {
                        this.formatPropertyData(this.categoryData[i].children[j].children[k].properties);
                        this.propertyData = this.categoryData[i].children[j].children[k].properties;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      formatPropertyData(obj) {
        let temp = [];
        for (let i = 0; i < obj.length; i++) {
          //propertyId
          temp[obj[i].id] = '';
        }
        this.otherForm = temp
      },
      cancelPutForm() {
        this.$router.go(-1)
      },
      toVerify() {
        this.$router.push(
          {
            path: 'verify',
            query: {
              goodsId: this.goodsId,
              verificationStatus: this.verificationStatus,
              status: this.submitForm.status
            }
          }
        )
      }
    },
    mounted() {
      window.scrollTo(0, 0)
      this.goodsId = this.$route.query.goodsId
      if (this.goodsId) {
        this.initForm()
        this.initTable()
      }
    },
  };
</script>
<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .search-box {
    position: relative;
    border-bottom: 1px solid #eee;
  }

  .consumer-page {
    position: relative;
    padding: 20px 40px;
  }

  .activity-list-page .el-checkbox + .el-checkbox {
    margin-left: 0 !important;
    margin-right: 30px !important;
  }

  .img-area {
    margin: 10px 0;
  }

  .img-wraper {
    float: left;
    width: 100px;
    height: 100px;
    border: dotted 1px rgba(0, 0, 0, .5);
    border-radius: 5px;
    margin: 0 10px;
  }

  .clearfix:after {
    content: '';
    display: block;
    overflow: hidden;
    clear: both;
  }

  /*显示大图的样式*/
  .mask {
    position: absolute;
    z-index: 2100;
    background-color: rgba(33, 33, 33, .2);
    margin: 0;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    -webkit-transition: opacity .3s;
    transition: opacity .3s;
  }

  .big-image {
    position: absolute;
    left: 50%;
    top: 360px;
    transform: translate(-50%, -50%);
    width: 800px;
    height: 600px;
    z-index: 2200;
  }
</style>
